// 更换新手机和邮箱
import email from '@/assets/email.png';
import tel from '@/assets/tel_g.png';
import CodeModal from '@/pages/Login/components/CodeModal';
import { handleEvent } from '@/services/center';
import { addMobileAuth, changeEmail, sendEmailCode, sendMobileCodeNT } from '@/services/login';
import { phonePattern } from '@/utils/common';
import { Button, Col, Divider, Form, Input, Modal, Row, message } from 'antd';
import { useEffect, useState } from 'react';
import { useIntl } from 'umi';
type Props = {
  visible: boolean;
  handleCancel: () => void;
  handleOk: (phone: string) => void;
  type?: string;
  tag?: string;
  title?: string;
};
let timer: any = null;
const ChangePhoneModal: React.FC<Props> = ({
  visible,
  handleCancel,
  handleOk,
  type = 'mobile',
  tag,
  title,
}) => {
  const [count, setCount] = useState(0);
  //  防止频繁点击
  const [isClick, setIsClick] = useState(false);
  // 是否
  const [isFirstClick, setIsFirstClick] = useState(false);
  const [codeModalvisible, setCodeModalvisible] = useState(false);
  const isPhone = type == 'mobile';
  const intl = useIntl();

  useEffect(() => {
    if (count == 59) {
      timer = setInterval(() => setCount((t) => t - 1), 1000);
    } else if (count <= 0) {
      clearInterval(timer);
    }
  }, [count]);
  const sendSuc = () => {
    setCount(59);
    setIsClick(false);
    setIsFirstClick(true);

    message.success(intl.formatMessage({ id: 'home.send_suc' }));
  };
  return (
    <Modal
      className="changeInfoModal"
      footer={false}
      width={480}
      closeIcon={null}
      open={visible}
      destroyOnClose
    >
      <div style={{ fontWeight: 'bold', fontSize: 24, marginBottom: 32 }}>
        {title ||
          intl.formatMessage({
            id: isPhone ? 'login.phone.change' : 'login.email.change',
          })}
      </div>
      <Form
        onFinish={async (values: { captcha: string; mobile: string; email: string }) => {
          const fn = isPhone ? addMobileAuth : changeEmail;
          const { code, message: msg } = await fn({ ...values });
          if (code == '100200') {
            message.success(msg);
            handleOk(values.mobile);
            if (tag) handleEvent(tag);
          }
        }}
        labelCol={{ span: 0 }}
      >
        <Form.Item
          label={intl.formatMessage({ id: isPhone ? 'login.phone.new' : 'login.email.new' })}
          rules={[{ required: true }, { ...(isPhone ? phonePattern : {}) }]}
          name={type}
          validateTrigger="onBlur"
        >
          <Input
            prefix={
              <>
                <img src={isPhone ? tel : email} width={14} style={{ marginRight: 5 }} />
                {isPhone ? <div style={{ color: '#333', marginLeft: 10 }}>+852</div> : null}
              </>
            }
            variant="filled"
            style={{ height: 60 }}
            placeholder={intl.formatMessage({
              id: isPhone ? 'login.phone.new' : 'login.email.new',
            })}
          />
        </Form.Item>
        <Form.Item
          noStyle
          shouldUpdate={(prevValues, curValues) => prevValues[type] !== curValues[type]}
        >
          {({ getFieldValue }) => {
            const mobile = getFieldValue(type);
            return (
              <Form.Item
                label={intl.formatMessage({ id: 'login.captcha' })}
                rules={[{ required: true }]}
                name="captcha"
              >
                <Input
                  variant="filled"
                  suffix={
                    <>
                      <Divider type="vertical" />
                      <Button
                        disabled={!!count || !mobile}
                        onClick={async () => {
                          if (isClick || !!count) {
                            return false;
                          }

                          setIsClick(true);
                          try {
                            if (isPhone) {
                              await sendMobileCodeNT({
                                mobile,
                                valType: 4,
                              });
                            }
                            if (type == 'email') {
                              await sendEmailCode({ type: 3, email: mobile });
                            }
                            sendSuc();
                          } catch {
                            setIsClick(false);
                          }
                        }}
                        style={{
                          border: 'none',
                          color: '#0070df',
                          background: 'none',
                          padding: '0',
                          boxShadow: 'none',
                        }}
                      >
                        {count == 0
                          ? isFirstClick
                            ? intl.formatMessage({ id: 'login.phone.send' })
                            : intl.formatMessage({ id: 'login.get' })
                          : intl.formatMessage({ id: 'login.count' }, { count: count })}
                      </Button>
                    </>
                  }
                  style={{ height: 60 }}
                  placeholder={intl.formatMessage({ id: 'login.captcha' })}
                />
              </Form.Item>
            );
          }}
        </Form.Item>
        <Col>
          <span
            style={{ color: '#0070df', cursor: 'pointer' }}
            onClick={() => {
              setCodeModalvisible(true);
            }}
          >
            {intl.formatMessage({ id: 'login.get_number' })}
          </span>
        </Col>
        <Row gutter={[24, 0]} style={{ marginTop: 40 }}>
          <Col span={12}>
            <Button onClick={handleCancel} className="cancel_btn">
              {intl.formatMessage({ id: 'home.cancel' })}
            </Button>
          </Col>
          <Col span={12}>
            <Form.Item style={{ marginBottom: 0 }}>
              <Button htmlType="submit" style={{ width: '100%', height: '60px' }} type="primary">
                {intl.formatMessage({ id: 'home.sure' })}
              </Button>
            </Form.Item>
          </Col>
        </Row>
      </Form>
      {/* 验证码弹窗 */}
      <CodeModal
        type={type}
        visible={codeModalvisible}
        handleCancel={() => {
          setCodeModalvisible(false);
        }}
      />
    </Modal>
  );
};

export default ChangePhoneModal;
